import {generateSuit} from "@/utils/artifact_utils";

export default class socketService {
    static instance = null

    static get Instance() {
        if (this.instance == null) {
            this.instance = new socketService()
        }
        return this.instance
    }

    ws = null
    callBackMapping = {}
    dmgData = []
    expectDmgData = []
    timesArray = []

    registerCallBack(socketType, callback) {
        console.log("{} register callback function", socketType)
        this.callBackMapping[socketType] = callback
    }

    unRegisterCallBack(socketType) {
        this.callBackMapping[socketType] = null
    }
    send(data){
        this.ws.send(data)
    }

    connect() {
        this.ws = new WebSocket("ws://localhost:11020/ys/dmg");
        this.ws.onopen = function () {
            console.log(1)
        }

        this.ws.onclose = function () {
            console.log(2)
        }
        this.ws.onmessage = msg => {
            const recvData = JSON.parse(msg.data)
            const expectDmgProperties = recvData.expectDmgProperties;
            const maxDmgProperties = recvData.maxDmgProperties;
            let suitExpect = generateSuit(expectDmgProperties,100,false);
            let suitMax = generateSuit(maxDmgProperties,10,false);

            this.expectDmgData.push(recvData.expectDmg)
            this.dmgData.push(recvData.maxDmg)
            this.timesArray.push(recvData.times)

            if (this.dmgData.length > 20) {
                this.dmgData.shift();
                this.expectDmgData.shift();
                this.timesArray.shift();
            }
            if(this.callBackMapping['trendData']!= null){
                this.callBackMapping['trendData'].call(this, this.dmgData, this.expectDmgData, this.timesArray,suitExpect,suitMax)
            }

        }
    }
}
